package com.example.a828502.httpHelper;

import android.content.Context;
import android.util.Log;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;


/**
 * Created by 828502 on 2016/5/17.
 */
public class GetTaskListHelper {
    protected Context mContext;
    private final OkHttpClient client = new OkHttpClient();
    private String results = "";

    public GetTaskListHelper(Context context) {
        this.mContext = context;
//        System.setProperty("http.keepAlive", "false");
    }

    public String requestHelper(String ip, String port)throws ParseException, IOException, JSONException {
//
//        String path = "http://"+ip+":"+port+HttpConstans.Method.GET_TASK_LIST; //组合请求地址

        String path = "http://10.118.44.71:8080/task/order/all";

        URL url = new URL(path);
        /**
         * 这里网络请求使用的是类HttpURLConnection，另外一种可以选择使用类HttpClient。
         */
        HttpURLConnection conn = (HttpURLConnection) url
                .openConnection();
        conn.setRequestMethod("GET");//使用GET方法获取
        conn.setConnectTimeout(5000);
        int code = conn.getResponseCode();
        if (code == 200) {
            /**
             * 如果获取的code为200，则证明数据获取是正确的。
             */
            InputStream is = conn.getInputStream();
            String result = HttpUtils.readMyInputStream(is);
            return result;
        }
        return null;
    }


    /**
     * OKHttp 方法请求未调通
     * @throws Exception
     */
    public String execute() throws Exception {
        Request request = new Request.Builder()
                .url("http://10.118.44.71:8080/task/order/all")
                .build();
        Call call = client.newCall(request);


        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                Log.i("_+_+_+_+", results);

            }
        });
        return results;
    }

}
